package com.lang8.util.i18n;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.lang8.util.file.FileUtil;

public class Resources {
	private static Resources instance = new Resources();
	private static boolean isInit = false;
	private Map<String, Properties> i18nMap = new HashMap<String, Properties>();
	private Resources(){}
	public static Resources getInstance(){
		if (!isInit) {
			synchronized (Resources.class) {
				if (!isInit) {
					instance.init();
				}
				isInit = true;
			}
		}
		return instance;
	}
	private void init() {
		File i18nRoot = new File(Resources.class.getResource("/com/lang8/config/i18n").getFile());
		File[] resourcesLocales = i18nRoot.listFiles();
		for (File resLoc : resourcesLocales) {
			String resLocName = resLoc.getName();
			Properties prop = loadProperties(resLoc);
			i18nMap.put(resLocName, prop);
		}
	}
	private Properties loadProperties(File resLoc) {
		File[] resourcesFiles = resLoc.listFiles();
		Properties prop = new Properties();
		for (File resFile : resourcesFiles) {
			InputStream is = null;
			try {
				is = new FileInputStream(resFile);
				prop.load(is);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				FileUtil.closeFile(is);
			}
		}
		return prop;
	}
	public static String getResources(String localeName, String key){
		Resources instance = getInstance();
		Properties prop = instance.i18nMap.get(localeName);
		if (prop == null) {
			prop = instance.i18nMap.get("en_US");
		}
		String value = prop.getProperty(key);
		if (value == null) {
			value = instance.i18nMap.get("en_US").getProperty(key);
			if (value == null) {
				throw new IllegalArgumentException("There's no key '" + key + "' found.");
			}
		}
		return value;
	}
	public static String getResources(String localeName, String key, String defaultValue){
		try {
			String value = getResources(localeName, key);
			return value;
		} catch (Exception e) {
			return defaultValue;
		}
	}
}
